<template>
    <div class="box">
        <div class="box-header">
            <span class="text-large font-600 mr-3"> {{state.title}} </span>
        </div>
        <div class="box-content">
            <div class="box-tree">
                <div class="tree-search">
                    <el-input v-model="state.keyword" placeholder="输入机构名称搜索" :suffix-icon="Search" />
                </div>
                <div class="tree-content">
                    <el-tree ref="treeRef" :props="props" node-key="id" @node-click="onNodeClick" :load="loadNode" lazy>
                        <template #default="scope">
                            <div class="custom-node">
                                <SvgIcon :name="scope.node.data.icon" />
                                <span>{{scope.node.label}}</span>
                            </div>
                        </template>
                    </el-tree>
                </div>
            </div>
            <div class="box-auth">
                <div class="auth-title">
                    <el-button type="primary" style="margin-left: 5px" :icon="Plus" @click="submitAuth">提交</el-button>
                    <el-button type="primary" style="margin-left: 5px" :icon="CirclePlus" @click="selectAll">全选
                    </el-button>
                    <el-button type="danger" style="margin-left: 5px" :icon="Refresh" @click="clearSelect">全部清除
                    </el-button>
                </div>
                <div class="auth-content">
                    <div v-for="item in state.authList" :key="item.key">
                        <div style="clear: both; padding-top: 2px">
                            <el-divider content-position="left">
                                {{ item.name }}
                                <el-button type="primary" @click="selectAllByKey(item.key)" link>全选</el-button>
                                <el-divider direction="vertical" />
                                <el-button type="primary" @click="clearAllByKey(item.key)" link>清除</el-button>
                            </el-divider>
                            <div class="auth-checkbox" v-for="ch in getNeedAuthInfo(item.children)" :key="ch.key" style="float: left">
                                <input type="checkbox" :data-key="item.key" name="authBox" :value="ch.value" :checked="ch.isAuth === 'yes'" />
                                {{ ch.name }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup name="permissionRelation">
import { Search, Plus, CirclePlus, Refresh } from "@element-plus/icons-vue";
import { ref, reactive, onMounted } from "vue";
import { ElMessageBox, ElMessage } from 'element-plus';
import { ElTree } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { useRoute, useRouter } from 'vue-router';
import { queryTree } from "/@/api/auth/menu";
import { fetchAuthList, doAuth } from "/@/api/auth/pr";

const route = useRoute();
const router = useRouter();


const state = reactive<any>({
    keyword: '',
    title: '',
    authList: [],
    targetId: null,
    status: null,
    pid: '' //选择的地址ID
})

const props = {
    label: 'title',
    children: 'children',
    isLeaf: 'leaf',
}

const treeRef = ref<InstanceType<typeof ElTree>>()

/******方法区******/
const goBack = () => {

}

const selectAllByKey = (key: string) => {
    let checkboxs = document.getElementsByName('authBox')
    for (let c of checkboxs) {
        if (key === c.dataset['key'] && c.checked === false) {
            c.checked = true
        }
    }
}
const clearAllByKey = (key) => {
    let checkboxs = document.getElementsByName('authBox')
    for (let c of checkboxs) {
        if (key === c.dataset['key'] && c.checked === true) {
            c.checked = false
        }
    }
}

const submitAuth = () => {
    let checkboxs = document.getElementsByName('authBox')
    let auths = []
    for (let c of checkboxs) {
        if (c.checked == true && !auths.includes(c.value)) {
            auths.push(c.value)
        }
    }
    // if (auths.length > 0) {
    //     if (dom && dom.length > 0) {
    //         if (!dom[0].checked) {
    //             dom[0].checked = true
    //             auths.push(dom[0].value)
    //         }
    //     }
    // }
    let content = '确定授权吗？'
    if (auths.length === 0) {
        // this.$message.warning('请选择需要授权的信息')
        content = '确定清空当前的权限吗？'
    }
    const str = auths.join('·')
    ElMessageBox.confirm(`确定提交授权信息吗?`,'提示', {type: 'warning'}).then(async () => {
        const res = await doAuth({ targetId: state.targetId, pid: state.pid, auths: str, status: state.status });
        if(res.code === 0) {
            ElMessage.success({ message: '授权成功' });
        }
    });
}
const clearSelect = () => {
    let checkboxs = document.getElementsByName('authBox')
    for (let c of checkboxs) {
        if (c.checked == true) {
            c.checked = false
        }
    }
}
const selectAll = () => {
    let checkboxs = document.getElementsByName('authBox')
    for (let c of checkboxs) {
        if (c.checked == false && c.disabled == false) {
            c.checked = true
        }
    }
}


const loadNode = async (node: Node, resolve: (data: Tree[]) => void) => {
    const da = node.data;
    const param = { pid: da.id }
    const res: any = await queryTree(param);
    if (res && res.code === 0) {
        var data = res.data
        return resolve(data)
    }
}

const getNeedAuthInfo = (child: any) => {
    let auths = []
    for (let c of child) {
        if (c.disable === 'no') {
            auths.push(c)
        }
    }
    return auths
}


const onNodeClick = async (data: any) => {
    state.pid = data.id
    var param = { status: state.status, targetId: state.targetId, pid: data.id };
    const res: any = await fetchAuthList(param);
    if (res.code === 0) {
        state.authList = res.data
    }
}

/******方法区******/

onMounted(() => {
    const { targetId, title, status } = route.query
    state.title = title;
    state.status = status
    state.targetId = targetId;
    if (status === '1' || status === '4') {
        state.title = `角色授权[${title}]`
    } else if (status === '2' || status === '3') {
        state.title = `用户授权[${title}]`
    }
});


</script>
  
<style lang="scss" scoped>
.box {
    background-color: #fff;
    display: flex;
    padding: 0 12px 12px;
    flex-direction: column;

    .box-header {
        padding:14px 6px;
        font-size:16px;
        text-align: center;
    }

    a {
        color: blue;
        cursor: pointer;
    }

    .box-content {
        display: flex;
        height: calc(100vh - 150px);
        border-top: 1px solid rgb(241, 242, 243);

        .box-tree {
            display: flex;
            width: 240px;
            border-right: 1px solid rgb(241, 242, 243);
            flex-direction: column;
            border-left: 1px solid rgb(241, 242, 243);
            border-bottom: 1px solid rgb(241, 242, 243);

            .tree-search {
                display: flex;
                width: 100%;
                padding: 6px;
                height: 40px;
            }

            .tree-content {
                display: flex;
                width: 100%;
                padding: 6px;
                flex: 1;

            }
        }

        .box-auth {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow-x: hidden;

            .auth-title {
                display: flex;
                padding: 6px;
                width: 100%;
                border-bottom: 1px solid rgb(241, 242, 243);
            }

            .auth-content {
                display: flex;
                flex: 1;
                padding: 12px;
                flex-direction: column;
                overflow-y: auto;
            }
        }
    }
}

.el-col {
    border-right: 1px solid rgb(241, 242, 243);
}

.auth-checkbox {
    float: left;
    width: 100px;
    height: 45px;
    text-align: center;
    line-height: 45px;
    border: 1px solid #dfe6ec;
}
</style>
  